/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rafkind.resrev.web.page;

import com.rafkind.resrev.dao.UserDao;
import com.rafkind.resrev.data.User;
import com.rafkind.resrev.web.Authorized;
import com.rafkind.resrev.web.Session;
import com.rafkind.resrev.web.page.component.AddUserButton;
import com.rafkind.resrev.web.page.component.EditOrDeleteUserPanel;
import com.rafkind.resrev.web.page.component.TitleMenu;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

/**
 *
 * @author dave
 */
@Authorized
public class UsersPage extends WebPage {
  @SpringBean
  private UserDao userDao;
  
  public UsersPage() {
    add(new TitleMenu("titleMenu"));
    
    List<IColumn<?>> columns = new ArrayList<IColumn<?>>();
    
    final Stylist stylist = new Stylist.ForUser();
    
    columns.add(
        new ColorfulPropertyColumn(new Model<String>("User"), "loginName", "loginName", stylist));
    
    columns.add(
        new ColorfulPropertyColumn(new Model<String>("Name"), "name", "name", stylist));
    
    columns.add(
        new ColorfulPropertyColumn(new Model<String>("Email"), "email", "email", stylist));
    
    columns.add(
        new ColorfulPropertyColumn(new Model<String>("Phone"), "phone", "phone", stylist));
    
    columns.add(
        new AbstractColumn<User>(new Model<String>("Authorizor")){
      public void populateItem(
          Item<ICellPopulator<User>> cellItem, 
          String componentId, 
          IModel<User> model) {
        Label label = null;
        if (model.getObject().getAuthorizor() != null) {
          label =
              new Label(
                componentId, 
                new PropertyModel(model, "authorizor.name"));
        } else {
          label = new Label(componentId, "");          
        }
        
        User u = model.getObject();
        label.add(new SimpleAttributeModifier(
          "style",
          stylist.getStyleFor(model.getObject())));
        
        cellItem.add(label);
      }
      @Override
      public String getSortProperty() {
        return "authorizor.name";
      }

      @Override
      public boolean isSortable() {
        return true;
      }
    });
    
    columns.add(
        new AbstractColumn<User>(new Model<String>("Admin")){
      public void populateItem(
          Item<ICellPopulator<User>> cellItem, 
          String componentId, 
          IModel<User> model) {
        
        Label label = new Label(
              componentId, 
              (model.getObject().isAdmin() ? "Yes" : ""));
        User u = model.getObject();
        label.add(new SimpleAttributeModifier(
          "style",
          stylist.getStyleFor(model.getObject())));
        
        cellItem.add(label);         
        
      }
      @Override
      public String getSortProperty() {
        return "admin";
      }
      @Override
      public boolean isSortable() {
        return true;
      }
    });
    
    columns.add(
        new ColorfulPropertyColumn(new Model<String>("Display Color"), "color", "color", stylist));
    
    columns.add(
        new ColorfulPropertyColumn(new Model<String>("Comment"), "comment", "comment", stylist){

      @Override
      public String getCssClass() {
        return "comment";
      }      
    });
    
    if (((Session)getSession()).getCurrentUser().isAdmin()) {
      columns.add(new AbstractColumn<User>(new Model<String>("Add New User")){

        public void populateItem(Item<ICellPopulator<User>> cellItem, 
            String id, 
            IModel<User> model) {

          cellItem.add(new EditOrDeleteUserPanel(id, model));
        }

        @Override
        public Component getHeader(String id) {
          return new AddUserButton(id, new Model(getPage()));
        }      
      });
    }
    
    add(new DefaultDataTable(
        "table", 
        columns, 
        new UserDataProvider(this), 
        10));
  }

  public UserDao getUserDao() {
    return userDao;
  }  
  
  public static class UserDataProvider extends SortableDataProvider<User> {

    private UsersPage usersPage;

    public UserDataProvider(UsersPage usersPage) {
      this.usersPage = usersPage;
      
      setSort("name", true);
    }    
    
    public Iterator<? extends User> iterator(int first, int count) {
      SortParam sp = getSort();      
      return usersPage.getUserDao()
          .getAllUsers(first, count, sp.getProperty(), sp.isAscending())
          .iterator();
    }

    public IModel<User> model(User user) {
      return new DetachableUserModel(usersPage.getUserDao(), user);
    }

    public int size() {
      return usersPage.getUserDao().countAllUsers();
    }    
  }
  
  public static class DetachableUserModel 
      extends LoadableDetachableModel<User> {

    private int id;
    private UserDao userDao;
    
    public DetachableUserModel(UserDao userDao, User user) {
      super(user);
      
      this.userDao = userDao;
      
      id = user.getId();
    }

    @Override
    public int hashCode() {
      int hash = 7;
      hash = 53 * hash + this.id;
      return hash;
    }   

    @Override
    public boolean equals(Object obj) {
      if (obj == null) {
        return false;
      }
      if (getClass() != obj.getClass()) {
        return false;
      }
      final DetachableUserModel other = (DetachableUserModel) obj;
      if (this.id != other.id) {
        return false;
      }
      return true;
    }        

    @Override
    protected User load() {
      return userDao.getUser(id);
    }    
  }
  
  /*public static class ColorfulPropertyColumn extends PropertyColumn<User> {

    public ColorfulPropertyColumn(IModel<String> arg0, String arg1) {
      super(arg0, arg1);
    }

    public ColorfulPropertyColumn(IModel<String> arg0, String arg1, String arg2) {
      super(arg0, arg1, arg2);
    }

    @Override
    public void populateItem(Item item, String componentId, IModel model) {
      User u = (User) model.getObject();
      Label label = new Label(componentId, createLabelModel(model));
      
      label.add(createUserColorAttribute(u));
      item.add(label);
    }       
  }
  
  private static SimpleAttributeModifier createUserColorAttribute(User u) {
    return new SimpleAttributeModifier(
            "style", 
            "color: " + 
            (u != null && u.getColor() != null 
              ? 
                u.getColor().getHexColor() 
              : 
                Color.DEFAULT.getHexColor()));
  }*/
}